import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { listRoles, getRole, getRolePermissions, setRolePermissions, getRoleUsers, setRoleUsers, createRole, updateRole, deleteRole } from '../api/role'

// 异步获取角色列表
export const fetchRoles = createAsyncThunk(
  'role/fetchRoles',
  async (params, { rejectWithValue }) => {
    try {
      const response = await listRoles(params)
      return response
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取角色列表失败' })
    }
  }
)

// 异步获取角色详情
export const fetchRoleDetail = createAsyncThunk(
  'role/fetchRoleDetail',
  async (id, { rejectWithValue }) => {
    try {
      const response = await getRole(id)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取角色详情失败' })
    }
  }
)

// 异步获取角色权限
export const fetchRolePermissions = createAsyncThunk(
  'role/fetchRolePermissions',
  async (id, { rejectWithValue }) => {
    try {
      const response = await getRolePermissions(id)
      return { id, permissions: response.data }
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取角色权限失败' })
    }
  }
)

// 异步设置角色权限
export const updateRolePermissions = createAsyncThunk(
  'role/updateRolePermissions',
  async ({ id, permissions }, { rejectWithValue }) => {
    try {
      await setRolePermissions(id, permissions)
      return { id, permissions }
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '设置角色权限失败' })
    }
  }
)

// 异步获取角色用户
export const fetchRoleUsers = createAsyncThunk(
  'role/fetchRoleUsers',
  async (id, { rejectWithValue }) => {
    try {
      const response = await getRoleUsers(id)
      return { id, users: response.data }
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取角色用户失败' })
    }
  }
)

// 异步设置角色用户
export const updateRoleUsers = createAsyncThunk(
  'role/updateRoleUsers',
  async ({ id, userIds }, { rejectWithValue }) => {
    try {
      await setRoleUsers(id, userIds)
      return { id, userIds }
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '设置角色用户失败' })
    }
  }
)

// 异步创建角色
export const addRole = createAsyncThunk(
  'role/addRole',
  async (roleData, { rejectWithValue }) => {
    try {
      const response = await createRole(roleData)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '添加角色失败' })
    }
  }
)

// 异步更新角色
export const editRole = createAsyncThunk(
  'role/editRole',
  async ({ id, data }, { rejectWithValue }) => {
    try {
      const response = await updateRole(id, data)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '更新角色失败' })
    }
  }
)

// 异步删除角色
export const removeRole = createAsyncThunk(
  'role/removeRole',
  async (id, { rejectWithValue }) => {
    try {
      await deleteRole(id)
      return id
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '删除角色失败' })
    }
  }
)

const initialState = {
  roles: [],
  currentRole: null,
  currentPermissions: [],
  roleUsers: {
    all: [],
    selected: []
  },
  pagination: {
    current: 1,
    pageSize: 10,
    total: 0
  },
  loading: false,
  error: null
}

const roleSlice = createSlice({
  name: 'role',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null
    },
    setCurrentPage: (state, action) => {
      state.pagination.current = action.payload
    },
    setPageSize: (state, action) => {
      state.pagination.pageSize = action.payload
    },
    clearCurrentRole: (state) => {
      state.currentRole = null
    },
    setCurrentPermissions: (state, action) => {
      state.currentPermissions = action.payload
    }
  },
  extraReducers: (builder) => {
    builder
      // 获取角色列表
      .addCase(fetchRoles.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchRoles.fulfilled, (state, action) => {
        state.loading = false
        state.roles = action.payload.data?.items || []
        state.pagination.total = action.payload.data?.total || 0
      })
      .addCase(fetchRoles.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取角色列表失败'
      })
      // 获取角色详情
      .addCase(fetchRoleDetail.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchRoleDetail.fulfilled, (state, action) => {
        state.loading = false
        state.currentRole = action.payload
      })
      .addCase(fetchRoleDetail.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取角色详情失败'
      })
      // 获取角色权限
      .addCase(fetchRolePermissions.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchRolePermissions.fulfilled, (state, action) => {
        state.loading = false
        state.currentPermissions = action.payload.permissions || []
      })
      .addCase(fetchRolePermissions.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取角色权限失败'
      })
      // 设置角色权限
      .addCase(updateRolePermissions.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(updateRolePermissions.fulfilled, (state, action) => {
        state.loading = false
        state.currentPermissions = action.payload.permissions
      })
      .addCase(updateRolePermissions.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '设置角色权限失败'
      })
      // 获取角色用户
      .addCase(fetchRoleUsers.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchRoleUsers.fulfilled, (state, action) => {
        state.loading = false
        state.roleUsers = action.payload.users || { all: [], selected: [] }
      })
      .addCase(fetchRoleUsers.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取角色用户失败'
      })
      // 设置角色用户
      .addCase(updateRoleUsers.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(updateRoleUsers.fulfilled, (state, action) => {
        state.loading = false
        state.roleUsers.selected = action.payload.userIds
      })
      .addCase(updateRoleUsers.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '设置角色用户失败'
      })
      // 添加角色
      .addCase(addRole.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(addRole.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(addRole.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '添加角色失败'
      })
      // 更新角色
      .addCase(editRole.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(editRole.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(editRole.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '更新角色失败'
      })
      // 删除角色
      .addCase(removeRole.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(removeRole.fulfilled, (state, action) => {
        state.loading = false
        state.roles = state.roles.filter(role => role.id !== action.payload)
      })
      .addCase(removeRole.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '删除角色失败'
      })
  }
})

export const { clearError, setCurrentPage, setPageSize, clearCurrentRole, setCurrentPermissions } = roleSlice.actions
export default roleSlice.reducer